package com.liupaik.pennmarketplace;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;


public class Listings extends BaseAdapter implements OnClickListener{
	
	private Context context;

    private List<Listing> listings;

    public Listings(Context context, List<Listing> listings) {
        this.context = context;
        this.listings = listings;
    }

    public int getCount() {
        return listings.size();
    }

    public Listing getItem(int position) {
        return listings.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup viewGroup) {
    	
        Listing entry = listings.get(position);
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.item, null);
        }
     
        
        //NORMAL LISTING
        if(!entry.getTitle().equals("")){
        	TextView title = (TextView)convertView.findViewById(R.id.title);
        	title.setText(entry.getTitle());
        }
        
        //REPLY WITH TEXT ONLY
        else if(!entry.getP_id().equals("")){     	
            String user = getUsername(entry.getU_id());
    		String name[];
    		name = user.split("@");
    		String username = name[0];
    		
        	TextView text = (TextView)convertView.findViewById(R.id.title);
        	text.setText(username+": "+entry.getText());
        }
        
        //REPLY WITH USER INFO AND TEXT
        else if(!entry.getU_id().equals("")){
            String user = getUsername(entry.getU_id());
    		String name[];
    		name = user.split("@");
    		String username = name[0];
    		
        	TextView text = (TextView)convertView.findViewById(R.id.title);
        	text.setText("Conversation with " + username);
        }
                
        return convertView;
    }

    public void onClick(View view) {
    	/*
        Listing entry = (Listing) view.getTag();
        
        Intent i = new Intent(context, Reply.class);
        i.putExtra("id", entry.getU_id());
        i.putExtra("U_id", entry.getU_id());
        i.putExtra("cat", entry.getCat());
        i.putExtra("title", entry.getTitle());
        i.putExtra("text", entry.getText());
        i.putExtra("time", entry.getTime());
        ((Activity) context).startActivityForResult(i, 0);   */
    }
    
public static final String USER = "http://www.upennakpsi.org/lololol/pennmarketplace/getusername.php";
	
	private String getUsername (String id) {

		InputStream is = null;

		String result = "";
		//LinkedList<String> listings = new LinkedList<String>();

		//the postings
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("id",id));
		//nameValuePairs.add(new BasicNameValuePair("U_id",U_id));
		//nameValuePairs.add(new BasicNameValuePair("P_id",P_id));
		//nameValuePairs.add(new BasicNameValuePair("text",text));

		//http post
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(USER);
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);            
			HttpEntity entity = response.getEntity();
			is = entity.getContent();                

		}catch(Exception e){
			//listings.add("Error in connecting...");
			result = "Error in connecting...";
			Log.e("log_tag", "Error in http connection "+e.toString());
			return result;
		}

		//convert response to string
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			is.close();
			result=sb.toString();
		}catch(Exception e){
			result = "Error in obtaining data...";
			Log.e("log_tag", "Error converting result "+e.toString());
			return result;
		}
		
		return result;
	}
}
